package com.demo.collector.netty.server;

import com.demo.collector.netty.NettyServer;
import com.demo.collector.netty.initializer.TempServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 沈伟峰
 */
@Slf4j
public class TempServer implements NettyServer {

    private final int port;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;

    public TempServer(int port) {
        this.port = port;
    }

    @Override
    public void start() {
        bossGroup = new NioEventLoopGroup();
        workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new TempServerInitializer());

            ChannelFuture channelFuture = serverBootstrap.bind(this.port).sync();
            log.info("{} 已启动，正在监听 {}", TempServer.class, channelFuture.channel().localAddress());
        } catch (Exception e) {
            this.close();
        }
    }

    @Override
    public void close() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}
